package com.woniu.car.controller;




import com.woniu.car.common.JWTUtil;
import com.woniu.car.common.ResponseEntity;
import com.woniu.car.domain.TRegistration;
import com.woniu.car.mapper.TRegistrationMapper;
import com.woniu.car.util.RegistrationUtil;
import io.swagger.annotations.Api;
import net.sf.json.JSONObject;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *测试通过
 * @author zhoubinbin
 * @since 2021-06-21
 */
@RestController
@RequestMapping("/tRegistration")
@Api(tags = "用户实名认证")
public class TRegistrationController {
    @Resource
    private TRegistrationMapper tRegistrationMapper;
    @GetMapping("certification")
    public ResponseEntity test(String realName, String identityNumber, HttpServletRequest request) throws Exception {
        String token = request.getHeader("token");
        if (token==null){
            throw new Exception("您当前未登陆，无法进行该操作");
        }
        String id = JWTUtil.getId(token);
        System.out.println(id);
        Integer userId = Integer.valueOf(id);
        String host = RegistrationUtil.host; // 【1】请求地址 支持http 和 https 及 WEBSOCKET
        String path = RegistrationUtil.path;// 【2】后缀
        String appcode = RegistrationUtil.appcode; // 【3】开通服务后 买家中心-查看AppCode
        if (realName==null&&identityNumber==null){
            throw new Exception("请输入正确的信息");
        }
        String idCard = identityNumber;// 【4】请求参数，详见文档描述
        String name = realName;// 【4】请求参数，详见文档描述
            String urlSend = host + path + "?idCard=" + idCard + "&name="+ URLEncoder.encode(name, "UTF-8");// 【5】拼接请求链接
            URL url = new URL(urlSend);
            HttpURLConnection httpURLCon = (HttpURLConnection) url.openConnection();
            httpURLCon.setRequestProperty("Authorization", "APPCODE " + appcode);//格式Authorization:APPCODE (中间是英文空格)
            int httpCode = httpURLCon.getResponseCode();
            if (httpCode == 200) {
                String json = read(httpURLCon.getInputStream());
                System.out.println("正常请求计费(其他均不计费)");
                System.out.println("获取返回的json：");
                System.out.print(json);

                //转成json形式
                JSONObject ss = JSONObject.fromObject(json);
                if (ss.getInt("status")==01){
                    TRegistration tRegistration = new TRegistration();
                    tRegistration.setIdentitySatus(0);
                    tRegistration.setIdentityNumber(identityNumber);
                    tRegistration.setRealName(realName);
                    tRegistration.setUserId(userId);
                    int insert = tRegistrationMapper.insert(tRegistration);
                    return new ResponseEntity(200,"认证成功",ss);
                }else{
                    return new ResponseEntity(400,ss.get("msg").toString(),ss);
                }

            } else {
                Map<String, List<String>> map = httpURLCon.getHeaderFields();
                String error = map.get("X-Ca-Error-Message").get(0);
                if (httpCode == 400 && error.equals("Invalid AppCode `not exists`")) {
                    System.out.println("AppCode错误 ");
                } else if (httpCode == 400 && error.equals("Invalid Url")) {
                    System.out.println("请求的 Method、Path 或者环境错误");
                } else if (httpCode == 400 && error.equals("Invalid Param Location")) {
                    System.out.println("参数错误");
                } else if (httpCode == 403 && error.equals("Unauthorized")) {
                    System.out.println("服务未被授权（或URL和Path不正确）");
                } else if (httpCode == 403 && error.equals("Quota Exhausted")) {
                    System.out.println("套餐包次数用完 ");
                } else {

                }

            }
        return new ResponseEntity(400,"认证失败,请检查姓名是否与身份证号符合",null);

    }
    /*
     * 读取返回结果
     */
    private static String read(InputStream is) throws IOException {
        StringBuffer sb = new StringBuffer();
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String line = null;
        while ((line = br.readLine()) != null) {
            line = new String(line.getBytes(), "utf-8");
            sb.append(line);
        }
        br.close();
        return sb.toString();
    }
}

